let cacheMessages: any;
function loadLang() {
    if (cacheMessages) {
        return cacheMessages;
    } else {
        const context: any = import.meta.glob('./lan/*.json', { eager: true });
        const messages: any = {};

        const langs = Object.keys(context);

        for (const key of langs) {
            const lang = context[key].default;            
            const name = key.replace(/(\.\/lan\/|\.json)/g, '');

            messages[name] = lang;
        }
        cacheMessages = messages;
        
        return messages;

    }
}
export const setLang = (lang?: string) => {
    lang ? sessionStorage.setItem('lang', lang) : (lang = (sessionStorage.getItem('lang') || "en"));

    return loadLang()[lang];
};

export const t = (str: string, mat?: Record<string, string | number>): string => {
    let message = setLang();
    
    const keys = str.split(".");
    keys.forEach(key => message = message[key]);

    if (mat) {
        Object.keys(mat).forEach(key => {
            message = message?.replace(`{${key}}`, "" + mat[key]);
        });
    }
    return message;
};

// console.log(t("report.t_13", { aa: 999 }));

